import { ref, onMounted, onUnmounted, readonly } from 'vue'

/**
 * 滚动检测Composable
 * 提供页面滚动状态检测和底部到达判断功能
 */
export function useScrollDetection() {
  // 当前滚动位置
  const scrollY = ref(0)
  // 页面总高度
  const pageHeight = ref(0)
  // 视窗高度
  const windowHeight = ref(0)
  // 是否接近底部（距离底部小于阈值）
  const isNearBottom = ref(false)
  // 是否已滚动到底部
  const isAtBottom = ref(false)
  // 滚动方向：'up' | 'down' | 'none'
  const scrollDirection = ref<'up' | 'down' | 'none'>('none')
  
  // 配置参数
  const BOTTOM_THRESHOLD = 100 // 距离底部多少像素时认为接近底部
  const SCROLL_THRESHOLD = 5   // 滚动多少像素才更新方向
  
  let lastScrollY = 0
  let ticking = false

  /**
   * 更新滚动状态
   */
  const updateScrollState = () => {
    const currentScrollY = window.scrollY
    const currentPageHeight = document.documentElement.scrollHeight
    const currentWindowHeight = window.innerHeight
    
    // 更新基础数据
    scrollY.value = currentScrollY
    pageHeight.value = currentPageHeight
    windowHeight.value = currentWindowHeight
    
    // 计算距离底部的距离
    const distanceToBottom = currentPageHeight - currentScrollY - currentWindowHeight
    
    // 更新底部状态
    isNearBottom.value = distanceToBottom <= BOTTOM_THRESHOLD
    isAtBottom.value = distanceToBottom <= 0
    
    // 更新滚动方向
    const scrollDiff = currentScrollY - lastScrollY
    if (Math.abs(scrollDiff) > SCROLL_THRESHOLD) {
      scrollDirection.value = scrollDiff > 0 ? 'down' : 'up'
      lastScrollY = currentScrollY
    }
    
    ticking = false
  }

  /**
   * 滚动事件处理器（使用requestAnimationFrame优化性能）
   */
  const handleScroll = () => {
    if (!ticking) {
      requestAnimationFrame(updateScrollState)
      ticking = true
    }
  }

  /**
   * 窗口大小变化处理器
   */
  const handleResize = () => {
    updateScrollState()
  }

  /**
   * 初始化滚动检测
   */
  const initScrollDetection = () => {
    // 初始化状态
    updateScrollState()
    
    // 添加事件监听器
    window.addEventListener('scroll', handleScroll, { passive: true })
    window.addEventListener('resize', handleResize, { passive: true })
  }

  /**
   * 清理滚动检测
   */
  const cleanupScrollDetection = () => {
    window.removeEventListener('scroll', handleScroll)
    window.removeEventListener('resize', handleResize)
  }

  /**
   * 获取滚动进度百分比（0-100）
   */
  const getScrollProgress = () => {
    if (pageHeight.value <= windowHeight.value) return 100
    return Math.min(100, Math.max(0, (scrollY.value / (pageHeight.value - windowHeight.value)) * 100))
  }

  /**
   * 平滑滚动到指定位置
   */
  const scrollToPosition = (position: number, behavior: ScrollBehavior = 'smooth') => {
    window.scrollTo({
      top: position,
      behavior
    })
  }

  /**
   * 平滑滚动到底部
   */
  const scrollToBottom = (behavior: ScrollBehavior = 'smooth') => {
    scrollToPosition(pageHeight.value - windowHeight.value, behavior)
  }

  /**
   * 平滑滚动到顶部
   */
  const scrollToTop = (behavior: ScrollBehavior = 'smooth') => {
    scrollToPosition(0, behavior)
  }

  // 组件挂载时初始化
  onMounted(() => {
    initScrollDetection()
  })

  // 组件卸载时清理
  onUnmounted(() => {
    cleanupScrollDetection()
  })

  return {
    // 状态
    scrollY: readonly(scrollY),
    pageHeight: readonly(pageHeight),
    windowHeight: readonly(windowHeight),
    isNearBottom: readonly(isNearBottom),
    isAtBottom: readonly(isAtBottom),
    scrollDirection: readonly(scrollDirection),
    
    // 方法
    getScrollProgress,
    scrollToPosition,
    scrollToBottom,
    scrollToTop,
    
    // 手动控制（高级用法）
    initScrollDetection,
    cleanupScrollDetection
  }
}

// 导出类型定义
export type ScrollDirection = 'up' | 'down' | 'none'
export type UseScrollDetectionReturn = ReturnType<typeof useScrollDetection>